#!/usr/bin/env python

import web
from web import form
import config
import md5
import sessions
import access
import utils

render = web.template.render('templates/', cache=config.template_cache)

login_form = form.Form(
        form.Textbox("username", form.notnull, class_="required"),
        form.Password("password", form.notnull, class_="required"),
        #form.Dropdown("language", ['en_us', 'zh_cn'])
        form.Dropdown("language", config.lang)
)

class omms_login:
    def GET(self):
        print render.login(login_form)

    def POST(self):
        i = web.input()
        user = utils.filter_auth(i.username)
        password = utils.filter_auth(i.password)
        lang = utils.filter_auth(i.language)

        m = md5.new()
        m.update(password)
        password = m.hexdigest()

        if not access.auth(user, password):
            return web.redirect('login?invalid=1')

        sid = sessions.new(user, {'username' : user, 'lang' : lang})
        web.setcookie('sid', sid)

        return web.redirect("/")

class omms_logout:
    def GET(self):
        sid = access.get_sid()
        if sid:
            sessions.destroy(sid)
            web.setcookie('sid', '')
        return web.redirect('/')
